package com.example.back.controller;

import com.example.back.entity.User;
import com.example.back.entity.otd.QueryPageDto;
import com.example.back.service.UserService;
import com.example.back.util.IpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/doLogin")
    public User doLogin(User user, HttpSession session) {
        User user1 = userService.selectUser(user);
        if(user1!=null){
            session.setAttribute("yhm",user1.getYhm());
        }
        return user1;
    }
    @PostMapping("/user")
    public int addUser(@RequestBody User user, HttpServletRequest request) {
        if (userService.queryUserByYhm(user.getYhm()) != null){return -1;
        }
        user.setIp(IpUtil.getClientIpAddress(request));
        return userService.addUser(user);
    }

    @DeleteMapping("/user/{id}")
    public int deleteUser(@PathVariable("id") Integer id) {
        return userService.deleteUser(id);
    }
    @PutMapping("/user")
    public int updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }
    @GetMapping("/user/{id}")
    public User queryUserById(@PathVariable("id") Integer id) {
        return userService.queryUserById(id);
    }
    @GetMapping("/user")
    public ArrayList<User> queryUser(User user) {
        return userService.selectUsers(user);
    }
    @GetMapping("/user/yhm/{yhm}")
    public User queryUserByYhm(@PathVariable("yhm")String yhm) {
        return userService.queryUserByYhm(yhm);
    }
    @GetMapping("/user/phone/{phone}")
    public User queryUserByPhone(@PathVariable("phone")String phone) {
        return userService.queryUserByPhone(phone);
    }
    @GetMapping("/user/list")
    public PageInfo<User> doList(User user, QueryPageDto pager) {
        // 分页
        PageHelper.startPage(pager.getPageNum(), pager.getPageSize());
        // 查询
        ArrayList<User> list = userService.selectUsers(user);
        // 返回分页信息
        return new PageInfo<User>(list);
    }
    @GetMapping("/user/email/{email}")
    public User queryUserByEmail(@PathVariable("email") String email) {
        return userService.queryUserByEmail(email);
    }

    @GetMapping("/user/fan/{userId}")
    public ArrayList<User> queryUserByFanId(@PathVariable("userId") Integer userId) {
        return userService.queryUserByFanId(userId);
    }
}
